package cn.psh.user.service.impl;

import cn.psh.basic.dto.EamilRegisterDto;
import cn.psh.basic.dto.RegisterDto;
import cn.psh.basic.util.MD5Utils;
import cn.psh.basic.util.StrUtils;
import cn.psh.basic.util.exception.BusinessException;
import cn.psh.user.domain.Logininfo;
import cn.psh.user.domain.User;
import cn.psh.user.mapper.LogininfoMapper;
import cn.psh.user.mapper.UserMapper;
import cn.psh.user.service.IUserService;
import cn.psh.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author pider
 * @since 2022-09-14
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void phoneRegister(RegisterDto registerDto) {
//        数据校验
        final String phone = registerDto.getPhone();
        final String smsCode = registerDto.getSmsCode();
        final String password = registerDto.getPassword();
        final String confirmPassword = registerDto.getConfirmPassword();

        if (phone == null || smsCode == null || password == null || confirmPassword == null) {
            throw new BusinessException("信息不能为空！！！");
        }
//        两次密码判断是否相同
        if(!password.equals(confirmPassword)){
            throw new BusinessException("两次密码不一致，请重新输入！！");
        }
//         校验验证码是否正确
        final Object phonecode = redisTemplate.opsForValue().get("register:" + phone);
        if(phonecode == null){
            throw new BusinessException("验证码失效请重新获取！！");
        }
        if(!smsCode.equals(phonecode.toString().split(":")[0])){
            throw new BusinessException("验证码不正确,请重新输入！");
        }
//        添加数据库
        User user =  registerDto2User(registerDto);
        Logininfo logininfo = user2logininfo(user);
//        先添加logininfo信息
        logininfoMapper.save(logininfo);
//        保存logininfo以后把自增id保存的user里面
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

    }

    /**
     * 邮箱注册
     * @param eamilRegisterDto
     */
    @Override
    public void eamilRegister(EamilRegisterDto eamilRegisterDto) {
//        数据校验
        final String email = eamilRegisterDto.getEmail();
        final String emailCode = eamilRegisterDto.getEmailCode();
        final String emailPassword = eamilRegisterDto.getEmailPassword();
        final String emailConfirmPassword = eamilRegisterDto.getEmailConfirmPassword();
        if(email==null || emailCode == null || emailPassword == null || emailConfirmPassword == null){
            throw new BusinessException("信息不能为空！！！");
        }
//        两次密码判断是否相同
        if(!emailPassword.equals(emailConfirmPassword)){
            throw new BusinessException("两次密码不一致，请重新输入！！");
        }
//         校验验证码是否正确
        final Object ecode = redisTemplate.opsForValue().get("register:" + email);
        if(ecode == null){
            throw new BusinessException("验证码失效请重新获取！！");
        }
        if(!emailCode.equals(ecode.toString().split(":")[0])){
            throw new BusinessException("验证码不正确，请重新输入！！");
        }
        //        添加数据库
        User user =  eamilRegisterDto2User(eamilRegisterDto);
        Logininfo logininfo = user2logininfo(user);
//        先添加logininfo信息
        logininfoMapper.save(logininfo);
//        保存logininfo以后把自增id保存的user里面
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);


    }

    private User eamilRegisterDto2User(EamilRegisterDto eamilRegisterDto) {
        final User user = new User();
        user.setUsername(eamilRegisterDto.getEmail());
        user.setEmail(eamilRegisterDto.getEmail());
//        盐值
        final String salt = StrUtils.getComplexRandomString(32);
//        MD5加密加盐值
        final String md5pwd = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5pwd);
        user.setState(1);
        return user;
    }

    private Logininfo user2logininfo(User user) {
        final Logininfo logininfo = new Logininfo();
//        copy
        BeanUtils.copyProperties(user,logininfo);
//        设置状态1用户 0管理员
        logininfo.setType(1);
//        注册后直接使用
        logininfo.setDisable(true);
        return logininfo;
    }


    private User registerDto2User(RegisterDto registerDto) {
        final User user = new User();
        user.setUsername(registerDto.getPhone());
        user.setPhone(registerDto.getPhone());
//        盐值
        final String salt = StrUtils.getComplexRandomString(32);
//        MD5加密加盐值
        final String md5pwd = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5pwd);
        user.setState(1);
        return user;
    }

    /**
     * 添加user的同时还要添加与之相关的logininfo表
     * @param user
     */
    @Override
    public void save(User user) {
//        盐值
        final String salt = StrUtils.getComplexRandomString(32);
        final String md5pwd = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5pwd);
//添加logininfo
        final Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);
//        设置user表中的logininfo_id添加
        user.setLogininfoId(logininfo.getId());
        super.save(user);
    }

    /**
     * 两个表的修改
     * @param user
     */
    @Override
    public void update(User user) {
        //        盐值
        final String salt = StrUtils.getComplexRandomString(32);
        final String md5pwd = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5pwd);
        final User olduser = userMapper.queryById(user.getId());
//        修改user信息
        user.setLogininfoId(olduser.getLogininfoId());
        super.update(user);
//        查询与该user相关的logininfo
        final Logininfo oldlogininfo = logininfoMapper.queryById(olduser.getLogininfoId());
//        把修改过的user数据直接copy到logininfo
        BeanUtils.copyProperties(user, oldlogininfo);
//        再修改logininfo
        logininfoMapper.update(oldlogininfo);

    }


    /**
     * 两张表的数据同时删除
     * @param id
     */
    @Override
    public void del(Long id) {
        User user = userMapper.queryById(id);
        super.del(id);
        logininfoMapper.del(user.getLogininfoId());
    }
}
